package com.beyond.flow.container

import com.beyond.flow.inter.UiEvent
import com.beyond.flow.inter.UiState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author chenshiyang
 * @time 2022/11/10 17:43
 * @name beyond-kotlin-frame
 * @class describe
 */
internal class RealContainer<S : UiState, E : UiEvent>(
    state: S,
    private val scope: CoroutineScope,
) : MutableContainer<S, E> {

    // UI状态使用了StateFlow，UI事件则使用SharedFlow（确保事件不会倒灌）。
    private val _stateFlow = MutableStateFlow(state)

    private val _eventFlow = MutableSharedFlow<E>()

    override val uiStateFlow: StateFlow<S> = _stateFlow

    override val uiEventFlow: Flow<E> = _eventFlow

    /**
     * 事件触发
     */
    override fun sendEvent(event: E) {
        scope.launch {
            _eventFlow.emit(event)
        }
    }

    /**
     * 数据更新
     */
    override fun updateState(action: S.() -> S) {
        _stateFlow.update { action(_stateFlow.value) }
    }
}

